package com.ptswitch.material.util.security;

import java.util.List;

import com.ptswitch.material.model.security.Permission;
import com.ptswitch.material.model.security.Role;

public class PermissionCheckUtil {

    public static boolean checkPermitted(String require, List<Role> roles) {
        if (roles == null) {
            return false;
        }
        for (Role role : roles) {
            if (checkPermitted(require, role)) {
                return true;
            }
        }
        return false;
    }

    public static boolean checkPermitted(String require, Role role) {
        for (Permission input : role.getPermissions()) {
            if (checkPermitted(require, input.getPermissionName())) {
                return true;
            }
        }
        return false;
    }

    public static boolean checkPermitted(String require, String input) {
        //a.b.c -> a , a.b , a.b.c
        //a.b.* -> a , a.b
        if (require.contains(input)) {
            return true;
        }
        //a.b.* (a.b) -> a.b.c1 , a.b.c2 , a.b.c.d
        if (require.endsWith("*")) {
            String requireParent = require.substring(0, require.length() - 2);
            return input.contains(requireParent);
        }
        return false;
    }

    public static String permittedAny(Permission permission) {
        return permission.getPermissionName() + ".*";
    }
}
